/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lge.clock.alarmclock;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.GetChars;
import android.widget.Toast;
import static android.provider.AlarmClock.ACTION_SET_ALARM;
import static android.provider.AlarmClock.EXTRA_HOUR;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
import static android.provider.AlarmClock.EXTRA_MINUTES;

import java.util.Calendar;
import com.lge.clock.util.Log;
import com.lge.clock.alarmclock.Alarms;
import com.lge.clock.alarmclock.AlarmMeta;

public class HandleSetAlarm extends Activity {
	
	private String TAG = "HandleSetAlarm";
 
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        android.util.Log.i(TAG, "onCreate");
    	ContentResolver resolver = this.getContentResolver();        
        String[] PROJECTION1 = new String[] { "_id" };
        Cursor cc = null;
		try {
			cc = resolver.query(Alarms.CONTENT_ALARMS_URI, PROJECTION1, null, null, null);
			if (cc != null) {
				if (cc.getCount() >= 15) {
					finish();
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if ( cc != null )
				cc.close();
		}
		
        Intent intent = getIntent();
        if (intent == null || !ACTION_SET_ALARM.equals(intent.getAction())) {
            finish();
            return;
        }

        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        final int hour = intent.getIntExtra(EXTRA_HOUR,
                calendar.get(Calendar.HOUR_OF_DAY));
        final int minutes = intent.getIntExtra(EXTRA_MINUTES,
                calendar.get(Calendar.MINUTE));
        String message = intent.getStringExtra(EXTRA_MESSAGE);
        if (message == null) {
            message = "";
        }
        
        android.util.Log.i(TAG, "message => " + message);
        
        ContentValues values = new ContentValues();
        values.put(AlarmMeta.COLUMNS.ALARM_HOUR,		hour);
        values.put(AlarmMeta.COLUMNS.ALARM_MINUTES,		minutes);
        values.put(AlarmMeta.COLUMNS.ALARM_DAYSOFWEEK,	0);
        values.put(AlarmMeta.COLUMNS.ALARM_ENABLED,		"1");
        values.put(AlarmMeta.COLUMNS.ALARM_SNOOZE,		"5");
        values.put(AlarmMeta.COLUMNS.ALARM_TONE,		defaultRingtone(this));
        values.put(AlarmMeta.COLUMNS.ALARM_VIB,			"On");
        values.put(AlarmMeta.COLUMNS.ALARM_PUZZLE,		"Off");        
        values.put(AlarmMeta.COLUMNS.ALARM_MEMO,		message);
        values.put(AlarmMeta.COLUMNS.ALARM_WIDGET_YN,	"N");
        resolver.insert(ALProvider.CONTENT_ALARMS_URI, values);

		int maxID = 0;
		
		String[] PROJECTION2 = new String[] { "max(_id) ID" };
		Cursor Cursor = null;
		try {
			Cursor = resolver.query(Alarms.CONTENT_ALARMS_URI, PROJECTION2, null, null, null);
			if (Cursor != null) {
				if (Cursor.moveToFirst()) {  
					maxID = Cursor.getInt(0);
					Log.d(TAG, "MAX ID=>" + maxID);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if ( Cursor != null )
				Cursor.close();
		}            
        ContentValues cvalues = null;
		cvalues	= new ContentValues();

		cvalues.put("hour", 		hour);
    	cvalues.put("minutes", 		minutes);     
		cvalues.put("daysofweek",   0);
		cvalues.put("enabled", 	    "1"); 
		cvalues.put("stop",  	    "");
		cvalues.put("aid",    		maxID);
		cvalues.put("aindex", 		0);
		cvalues.put("status", 		"A");
		resolver.insert(ALProvider.CONTENT_CALCU_URI, cvalues);
		if (maxID != 0) {
        	Alarms.enableAlarm(this, maxID, true);
		}
		else {
			Alarms.setNextAlert(this);
		}    			

        finish();
    }
    
    private void showToast(String message){
    	Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
	private static final String[] MEDIA_INTERNAL_COLUMNS = new String[] {
		android.provider.BaseColumns._ID,
		android.provider.MediaStore.MediaColumns.TITLE,
		"\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
		android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY  
	};
	
	public String defaultRingtone(Context context) {
		String defaultTone = "";
		Uri alert = RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM);
		
		if (alert == null) {
			defaultTone = "Off";  
			return defaultTone ;
		}
		
		String temp = defaultRingtoneTitle(context);
		Log.d(TAG, "=>" + temp + "<=" );
		
		ContentResolver resolver = context.getContentResolver();
		Cursor cur = null;
		try {
			cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, MEDIA_INTERNAL_COLUMNS,
		               "is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); 
			if (cur != null && cur.moveToFirst()) {
				do {
					Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
					int aa = (cur.getString(1)).indexOf( temp );
					if ( aa >=0 ) {
						Log.d(TAG, temp + " / Title=" +  cur.getString(1)  +   "<==  URI ==>" + uri1.toString());
						defaultTone	= uri1.toString();	
						break;
					}
				} while (cur.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cur != null)
				cur.close();
		}
		    
		if ("".equals(defaultTone.trim())) {
			defaultTone = "Off";
		}
		      
		Log.d(TAG, "====defaultTone======>" +  defaultTone );
		return defaultTone;
	}
	
	private String defaultRingtoneTitle(Context context) 
	{
		Uri alert = RingtoneManager.getActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM);
		
		if (alert != null) {
			final Ringtone r = RingtoneManager.getRingtone(context, alert);
			if (r != null) {
		    	Log.d(TAG, "=default===> " + r.getTitle(context) );
		    	return r.getTitle(context);  
		    }
		}	
		return "";
	}
}
